package com.ravi.queue;

import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class StringQueueUtil {

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	/**
	 * 入队
	 * @param roomCode 诊室编码
	 * @param checkupCode 体检号，唯一标识
	 */
	public  void addPatient2Queue(String roomCode, String checkupCode) {
		stringRedisTemplate.opsForList().rightPush(roomCode, checkupCode);
	}

	/**
	 * 队长
	 * @param roomCode 诊室编码
	 * @return Long长度
	 */
	public  Long getQueueLength(String roomCode) {
		return stringRedisTemplate.opsForList().size(roomCode);
	}

	// 获取队列数据
	public List<String> getQueueData(String roomCode) {
		return stringRedisTemplate.opsForList().range(roomCode, 0, -1);
	}

	// 某人中途离开队伍
	public  void leaveQueue(String roomCode, String checkupCode) {
		stringRedisTemplate.opsForList().remove(roomCode, 0, checkupCode);
	}

	// 队首离队
	public  String headLeaveQueue(String roomCode) {
		return stringRedisTemplate.opsForList().leftPop(roomCode);
	}

	// 得到某人队列中的位置
	public  List<Integer> getOnesPosition(String roomCode, String checkupCode) {
		List<String> queueData = getQueueData(roomCode);
		int myPositionBeforeNum = queueData.indexOf(checkupCode);
		int myPosition = myPositionBeforeNum + 1;
		int size = queueData.size();
		// 当前排队res[0]人，您排在第res[1]位，前面还有res[2]位。
		List<Integer> result = new ArrayList<>();
		result.add(size);
		result.add(myPosition);
		result.add(myPositionBeforeNum);
		return result;
	}

	// 插队操作
	public  void jumpAQueue(String roomCode, String jumpCheckupCode, String targetCheckupCode, Integer jumpType) {
		// 在target前面插队
		if (jumpType.equals(1)) {
			stringRedisTemplate.opsForList().leftPush(roomCode, targetCheckupCode, jumpCheckupCode);
		}
		if (jumpType.equals(2)) {
			stringRedisTemplate.opsForList().rightPush(roomCode, targetCheckupCode, jumpCheckupCode);
		}
	}
}
